# -*- coding: utf-8 -*-
import json
import requests
from .result import result
from bs4 import BeautifulSoup
# from ..common import save_userinfo
# from ..common import query_userinfo

CHECK_SSFW_URL = 'http://ssfw.hlju.edu.cn/ssfw/j_spring_ids_security_check'
PYFADM_ID_URL = "http://ssfw1.hlju.edu.cn/ssfw/zhcx/pyfa/xsfaTree.do"
NODE_URL='http://ssfw1.hlju.edu.cn/ssfw/zhcx/pyfa/node.do'
REAL_NAME_URL='http://my.hlju.edu.cn/index.portal'

# from NODE_URL get the pyfadm id,use this get node data
def request_pyfadm(token):

    check_cookie={'iPlanetDirectoryPro':token}

    # if there is no data after tried 10 times, return None
    loc_result = None

    for i in range(10):
        print('request pyfadm: ',i)
        if loc_result != None:
            break
        try:
            check_res = requests.get(CHECK_SSFW_URL,cookies = check_cookie,timeout=2,allow_redirects=False)
            j_cookie = check_res.headers.get('Set-Cookie').split(';')[0].split('=')[1]

            new_cookie={'iPlanetDirectoryPro':token,'JSESSIONID':j_cookie}
            new_res = requests.get(PYFADM_ID_URL,cookies=new_cookie,timeout=2,allow_redirects=False)

            # get Location value in headers,and the pyfadm id at the tial of this value
            loc_result = new_res.headers.get('Location').split('=')[1]
        except Exception as e:
            print(' request pyfadm error ',e)
            continue

    # # if loc result is none after 10 tried,it means verify expired
    # if loc_result == None:
    #     return '108'

    return loc_result

# get node data, this node is a json data from hlju web
def request_node(pyfadm,token):

    # pyfadm = request_pyfadm(token)
    # if pyfadm == None:
    #     return None
    # if pyfadm == '108':
    #     return '108'

    param ={'pyfadm':pyfadm,'nodeType':'-99','nodeValue':'root','sfggkz':'0'}

    payload={'param':json.dumps(param)}
    cookie = {'iPlanetDirectoryPro':token}

    # tried 10 times
    for i in range(10):
        print('request node: ',i)
        try:
            res = requests.get(NODE_URL,cookies=cookie,params=payload,timeout=2)
            res.encoding = res.apparent_encoding
            if res.status_code == 200:
                return res.text
        except Exception as e:
            print('request node error ',e)
            continue
    return None

def request_real_name(token):

    cookie = {'iPlanetDirectoryPro':token}

    realName = None
    for i in range(10):
        print('request real name: ',i)
        if realName != None:
            break
        try:
            session = requests.session()
            # session.get(CHECK_SSFW_URL,cookies = cookie,timeout=5)
            html = session.get(REAL_NAME_URL,cookies = cookie,timeout=5).content
            print(html)
            soup = BeautifulSoup(html,'html.parser').find('li',{'id':'welcomeMsg'})

            realName = soup.get_text(strip=True).split('，')[0]
            session.close()

        except Exception as e:
            print('request realName error ',e)
            continue

    return realName


def request_userinfo(uid,token):
    # user = query_userinfo(uid)
    user = None
    if user != None:
        return result(100,[{'uid':user.uid,'name':user.name,'college':user.college,'grade':user.grade,'specialty':user.specialty}])
    else:
        pyfadm = request_pyfadm(token)

        if pyfadm == None:
            return result(107)

        node = request_node(pyfadm,token)
        real_name = request_real_name(token)

        # if either node or real_name is none,means verify expired
        if node == None or real_name == None:
            return result(106)

        data = json.loads(node)
        re = result(100,[{'uid':uid,'name':real_name,'college':data['dwmc'],'grade':data['njmc'],'specialty':data['zymc']}])
        # save_userinfo(re)
        return re

# old method use uid & pwd
# def get_userinfo(userinfo_list):
#     return result(100,'ok',userinfo_list)

if __name__ == '__main__':
    data = request_userinfo('20135081','AQIC5wM2LY4SfcwhZFHdIp3eGrSeRSAWDk9%2FJg1T52u23OU%3D%40AAJTSQACMDI%3D%23').encode('utf-8')
    print(data)
